/*
 * Copyright (c) 2025 Huawei Device, Inc. Ltd. and <马弓手>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "Base64ToGallery.h"
#include "FileCache.h"
REGISTER_PLUGIN_CLASS(Base64ToGallery)
bool Base64ToGallery::execute(const string&  action, cJSON* args, CallbackContext cbc)
{
    if(action == "onArKTsResult") {
        return onArKTsResult(args);
    }
    m_cbc = cbc;
    string base64 = cJSON_GetArrayItem(args, 0)->valuestring;
    string filePrefix = cJSON_GetArrayItem(args, 1)->valuestring;
    bool mediaScannerEnabled = false;
    if(cJSON_GetArrayItem(args, 2)->type == cJSON_True) {
        mediaScannerEnabled = true;
    }
    if(base64.empty()) {
        cbc.error("Missing base64 string");
        return true;
    }
    
    int nSize = 0;
    const char* decodeString = CBase64::decode(base64.c_str(), nSize);
    if(nSize <= 0) {
        cbc.error("Missing base64 string");
        return true;
    }
    time_t seconds;
    seconds = time(NULL);
    char szBuf[32];
    sprintf(szBuf, "%d.png", seconds);
    string strFilePath = Application::g_databaseDir.substr(0, Application::g_databaseDir.find("database")-1)+"/base/temp/" + filePrefix + szBuf;
    
    if(!FileCache::writeFile(strFilePath, decodeString, nSize)) {
        cbc.error("Missing base64 string");
        return true;
    }
    return executeArkTs("/pages/SaveButtonImg", 0, strFilePath.c_str(), "Base64ToGallery", cbc);
}

bool Base64ToGallery::onArKTsResult(cJSON* args)
{
    string content = cJSON_GetObjectItem(args, "content")->valuestring;
    cJSON* json = cJSON_GetObjectItem(args, "result");
    if(json != NULL && json->type == cJSON_Array) {
        int count = cJSON_GetArraySize(json);
        if(count > 0) {
            string result = cJSON_GetArrayItem(json, 0)->valuestring;
            m_cbc.success(result);
        } else {
            m_cbc.error(content);
        }
    }
    return true;
}